<?php

namespace app\admin\controller;

use app\BaseController;
use frame\lib\VerfiyParam;

class Config extends BaseController
{
    public function index()
    {
        $data = include ROOT_PATH . 'config/system.php';
        $time = $data['other']['reg_vip_time'];
        $data['other']['reg_vip_time'] =  $time / (3600 * 24) . '天';
        $this->view('index', ['data' => $data]);
    }
    public function set()
    {
        $param = $_POST;
        $param['is_log'] = isset($param['is_log']) ? 1 : 0;
        $param['site'] = isset($param['site']) ? 1 : 0;
        $param['is_reg'] = isset($param['is_reg']) ? 1 : 0;
        $param['is_sign'] = isset($param['is_sign']) ? 1 : 0;
        $param['feedback'] = isset($param['feedback']) ? 1 : 0;
        $rule = [
            'is_log|登录开关' => 'in:1,0',
            'is_reg|注册开关' => 'in:1,0',
            'is_sign|签到开关' => 'in:1,0',
            'sign_three|连续签到3天' => 'int|gt:0',
            'sign_seven|连续签到7天' => 'int|gt:0',
            'sign_fifteen|连续签到15天' => 'int|gt:0',
            'reg_vip_time|注册送VIP时长' => 'int',
            'log_send_score|每日登录送积分' => 'int',
            'reg_send_score|注册送积分' => 'int'
        ];

        VerfiyParam::init($param, $rule);
        $confPath = ROOT_PATH . 'config/system.php';
        $data = include $confPath;
        if ($data['other']['reg_vip_time'] == $param['reg_vip_time']) {
            $param['reg_vip_time'] = $data['other']['reg_vip_time'];
        }
        $tmpText = '';
        foreach ($param as $k => $v) {
            $text = $tmpText != '' ? $tmpText :  file_get_contents($confPath);
            preg_match("/(.*)$k(.*)/", $text, $match);
            if (isset($match[0])) {
                $changeVal = str_replace($match[0], "'{$k}' => '{$v}',", $text);
                $tmpText = $changeVal;
            }
        }
        if (file_put_contents($confPath, trim($tmpText))) success();
        error();
    }
}
